package com.wx.web.controller.push;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.eachonline.core.JsonResult;
import com.eachonline.util.StringUtil;
import com.wx.business.model.ContentModel;
import com.wx.business.util.ParamException;
import com.wx.web.common.ServletUtill;
import com.wx.web.common.WXHttpUtil;

@Controller
@RequestMapping("/push")
public class WXPushMessage {

	
	@RequestMapping(value = "/wxInfo", method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult testInfo(HttpServletRequest  request ,String openid,int templateCode,HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        
        String touser="";
        if(StringUtil.isEmpty(openid))
        {
        	touser="o26qB0ZZoLnP8_7FokXdOb6Vb81I";
        }else{
        	touser=openid;
        }
         
        //解析请求参数转换成Map
        Map<String,Object> pushData=ServletUtill.getParameterMap(request);
        
        //根据templateCode和请求参数templateCode组装推送信息
        Map<String, Object> data;
		try {
			data = assemblePushTemplate(templateCode, pushData);
			 data.put("touser", touser);
		        
	         //从微信获取access_token ，然后推送信息是带过去
	        JSONObject object=JSONObject.parseObject( WXHttpUtil.requestAccessToken());
	        WXHttpUtil.sendTemplateMsg(object.getString("access_token"), JSONObject.toJSON(data).toString());
	        
	        System.out.println(JSONObject.toJSON(data).toString());  
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParamException e) {
			// TODO Auto-generated catch block
			return new JsonResult(false,e.getMessage() );
		}
		return new JsonResult(true, "推送成功");
		
	}
	
	/**
	 * 组装推送信息
	 * @param templateCode
	 * @return
	 * @throws IOException 
	 * @throws DocumentException 
	 * @throws ParamException 
	 */
	public Map<String,Object>  assemblePushTemplate(int templateCode,Map<String,Object> pushData) throws DocumentException, IOException, ParamException
	{		
		
		 Map<String,Object> data=new HashMap<String, Object>();
		 Map<String,Object> valuedatail= new  HashMap<String,Object>();
		 
		 //根据templateCode获取推送的模板
		 Map<String,Object> templateMap=getPushTemplate() ;
		 Map<String,Object> detailMap=(Map<String, Object>) templateMap.get(templateCode+"");
		 
		 
		 String templateId=detailMap.get("templateId")+"";
	     String  url=detailMap.get("url")+"";
		 List<Object> pushParamList=(List<Object>) detailMap.get("msg");
		 //组装推送信息
		 for(Object param:pushParamList)
		 {
			 if(StringUtil.isEmpty(pushData.get(param+"")+"")||pushData.get(param+"")==null)
			 {
				 throw new ParamException(param+"不能为空或者没有该参数");
				 
			 }
		     ContentModel  Content=new  ContentModel(pushData.get(param+"")+"", "#173177");
		     valuedatail.put(param+"", Content);
		 }
	
		data.put("template_id", templateId);
  	    data.put("data", valuedatail);
  	    data.put("url", url);
		
		return  data;
	}
	
	
        
	/**
	 * 解析推送配置模板，
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	 public  Map<String,Object> getPushTemplate() throws DocumentException, IOException {
		 //加载配置文件
		 Resource resource = new ClassPathResource("pushConfig.xml");
		 SAXReader reader = new SAXReader();
		 Document document = reader.read(resource.getFile());
		 Element root = document.getRootElement();
		 List<Element> childElements = root.elements();
		 
		 Map<String,Object> allPush=new HashMap<String, Object>();
		 //解析pushNode节点
		 for (Element childNode : childElements) {
			  List<Element> childNodeList=childNode.elements();
			  Map<String,Object> pushdata=new HashMap<String,Object>();
			  String code="";
			  for(Element child:childNodeList)
			  {
				  if("code".equalsIgnoreCase(child.getName()))
				  {
					  code= child.getStringValue();
				  }
				  
				  if("url".equalsIgnoreCase(child.getName()))
				  {
					  pushdata.put("url", child.getStringValue());
				  }
				  if("templateId".equalsIgnoreCase(child.getName()))
				  {
					  pushdata.put("templateId", child.getStringValue());
				  }
				  if("msg".equalsIgnoreCase(child.getName()))
				  {
					 List<String> textList=new ArrayList<String>(); 
					  //解析msg节点
					  List<Element> msgNodeList=child.elements();
					  for (Element node:msgNodeList) {
						  textList.add(node.getStringValue());
					   }
					  pushdata.put("msg", textList);
				  }
			  }
			  allPush.put(code, pushdata);
		  }
		 System.out.println(allPush.toString());
		 return allPush;
		
	    }

    
	
}
